/*******************************************************************************
 * Copyright (c) 2010 liw.
 * All rights reserved. 
 * 
 * This file is part of VanBus.
 * 
 *     VanBus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     VanBus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with VanBus.  If not, see <http://www.gnu.org/licenses/>.
 * Contributors:
 *     liw - initial API and implementation
 ******************************************************************************/
package org.niclab.vanbus.activity;

import java.util.EnumSet;

import org.niclab.vanbus.R;
import org.niclab.vanbus.activity.FavoritesTab.FavListUpdateBroadcastReciver;
import org.niclab.vanbus.activity.RouteListOfStopAct.StopMenuItem;
import org.niclab.vanbus.activity.comp.MenuDialog;
import org.niclab.vanbus.activity.controller.ReminderController;
import org.niclab.vanbus.database.ApplicationDataBase;
import org.niclab.vanbus.database.ReminderDAO;
import org.niclab.vanbus.model.EndStopReminder;
import org.niclab.vanbus.model.Reminder;
import org.niclab.vanbus.model.Reminder.ReminderType;
import org.niclab.vanbus.query.command.ShowDialogCmd;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter.ViewBinder;

public class RemindersTab {
	
	
	private enum AccordionStatus{
		StartStopReminders,EndStopReminders
	}
	
	private enum MenuItem{
		CancelReminder("Cancel Reminder");
		
		private String str;
		
		MenuItem(String str){
			this.str= str;
		}
		
		public String toString(){
			return this.str;
		}
	}
	
	private class ReminderMenuDialog extends MenuDialog<MenuItem>{
		
		
		EnumSet<MenuItem> set = EnumSet.allOf(MenuItem.class);
		public ReminderMenuDialog(Activity ownerActivity) {
			super(ownerActivity,android.R.layout.select_dialog_item,MenuItem.class);
			
		}


		@Override
		public void decorateMenu(AlertDialog dialog) {
			dialog.setTitle("Reminder Menu");
		}

		@Override
		public void onItemSelected(MenuItem selected) {
			
			switch(selected){
			case CancelReminder:cancelReminder();break;
			
			}
		}
		

		public void prepareMenuDialog(Dialog dialog) {
			
			super.prepareMenuDialog(dialog, set);
			
		}
		
	}

	private final static String LOG_TAG="RemindersTab";

	private int REMINDER_MENU_DIALOG;
	private TabActivity tabActivity;
	private Context context;
	private AccordionStatus remindersStat;


	private Button startStopRemindersBtn;
	private ListView startStopRemindersListView;
	private SimpleCursorAdapter startStopRemindersAdapter;
	
	private Button endStopRemindersBtn;
	private ListView endStopRemindersListView;
	private SimpleCursorAdapter endStopRemindersAdapter;
	
	
	private BroadcastReceiver receiver;
	private int selectedRowPosition;
	private View selectedRowView;
	private Cursor selectedRowItem;
	private ReminderMenuDialog reminderMenuDialog;
	
	public RemindersTab(TabActivity tabActivity){
		this.tabActivity = tabActivity;
		this.context = tabActivity.getApplicationContext();
		TabHost tabHost = tabActivity.getTabHost();
		TabHost.TabSpec spec = tabHost.newTabSpec(tabActivity.getString(R.string.reminders_tab_title))
									.setIndicator(tabActivity.getString(R.string.reminders_tab_title))
									.setContent(R.id.reminders_tab);
		tabHost.addTab(spec);
		

	}
	
	
	public void cancelReminder() {
		Cursor cursor = getSelectedRowItem();
	
		if(cursor.moveToFirst()){

			ReminderController reminderCtr = new ReminderController(context);
			int dbId = cursor.getInt(cursor.getColumnIndex("_id"));
			String reminderId = cursor.getString(cursor.getColumnIndex("REMINDER_ID"));
			Reminder.ReminderType type = Reminder.ReminderType.parseReminderType(cursor.getString(cursor.getColumnIndex("TYPE")));
			if(type == Reminder.ReminderType.StartStopReminder)
				reminderCtr.cancelStartStopReminder(dbId, reminderId);
			else
				reminderCtr.cancelEndStopReminder(dbId, reminderId);
			
		}
		
		
	}


	public void onPrepareDialog(final int id, final Dialog dialog){
		if(id == REMINDER_MENU_DIALOG){
			  reminderMenuDialog.prepareMenuDialog(dialog);
			
		}
	

		
	}

	public Dialog onCreateDialog(int id){
		Dialog dialog =null;
		if(id == REMINDER_MENU_DIALOG){
			dialog = reminderMenuDialog.createMenuDialog();
			return dialog;
		
		}
		
		return dialog;
		
		
		
	}

	
	public void onCreate(){
		
		reminderMenuDialog = new ReminderMenuDialog(tabActivity);
		this.REMINDER_MENU_DIALOG = ((VanBusAct)tabActivity).registerDialog();

		remindersStat = AccordionStatus.StartStopReminders;
		
		startStopRemindersBtn = (Button) tabActivity.findViewById(R.id.start_stop_reminder_button);
		startStopRemindersListView = (ListView) tabActivity.findViewById(R.id.start_stop_reminder_list);
		initializeStartStopRemindersList();
		startStopRemindersListView.setAdapter(startStopRemindersAdapter);

		startStopRemindersBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(remindersStat == AccordionStatus.StartStopReminders)
					return;
				
				startStopRemindersListView.setVisibility(View.VISIBLE);
				endStopRemindersListView.setVisibility(View.GONE);
				
				remindersStat = AccordionStatus.StartStopReminders;
				
			}
		});
		
		endStopRemindersBtn = (Button) tabActivity.findViewById(R.id.end_stop_reminder_button);
		endStopRemindersListView = (ListView) tabActivity.findViewById(R.id.end_stop_reminder_list);
		initializeEndStopRemindersList();
		endStopRemindersListView.setAdapter(endStopRemindersAdapter);
		endStopRemindersBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(remindersStat==AccordionStatus.EndStopReminders)
					return;
				
				startStopRemindersListView.setVisibility(View.GONE);
				endStopRemindersListView.setVisibility(View.VISIBLE);
				
				remindersStat = AccordionStatus.EndStopReminders;
					
				
			}
		});
		
		
		registerBroadcastReceiver();
	}
	
	
	private void initializeEndStopRemindersList() {
		Cursor remindersCursor = getRemindersCursor(ReminderType.EndStopReminder);
		
		String[] cols = {"ROUTE_ID","ROUTE_NAME","ROUTE_DIR","STOP_ID","STOP_NAME"};
		int[] views = {R.id.reminder_route_id,R.id.reminder_route_name,R.id.reminder_route_dir,R.id.reminder_stop_id,R.id.reminder_stop_name};
		
		endStopRemindersAdapter = new SimpleCursorAdapter(context,R.layout.reminder_end_stop_row, remindersCursor, cols,views);
		
		endStopRemindersAdapter.setViewBinder(new ViewBinder(){

			@Override
			public boolean setViewValue(View view, Cursor cursor,
					int columnIndex) {
				
				if(columnIndex ==cursor.getColumnIndex("ROUTE_NAME")){

					String value = cursor.getString(columnIndex);
					((TextView)view).setText(value.substring(value.indexOf('-')+1));
					
					return true;
					
				}

				return false;
			}
			
			
			
		});
		
		endStopRemindersListView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> adpater, View view, int position,
					long arg3) {
				Cursor cursor = (Cursor) endStopRemindersAdapter.getItem(position);
				setSelectedRow(position,view,cursor);			
				tabActivity.showDialog(REMINDER_MENU_DIALOG);
				
				
			}
			
		});
		
	}


	private void setSelectedRow(int position, View row, Cursor cursor) {
		this.selectedRowPosition = position;
		this.selectedRowView = row;
		this.selectedRowItem = cursor;
		
	}
	
	


	public int getSelectedRowPosition() {
		return selectedRowPosition;
	}


	public View getSelectedRowView() {
		return selectedRowView;
	}

	

	public Cursor getSelectedRowItem() {
		return selectedRowItem;
	}


	private Cursor getRemindersCursor(ReminderType type){
		ReminderDAO reminderDao = new ReminderDAO(ApplicationDataBase.getSQLiteOpenHelper());
		Cursor cursor = reminderDao.getReminders(-1, type);
		Log.v(LOG_TAG, TextUtils.join(" ",cursor.getColumnNames()));
		Log.v(LOG_TAG, "start stop reminders :" + cursor.getCount());
		return cursor;
	}
	
	private void initializeStartStopRemindersList() {
		
		Cursor remindersCursor = getRemindersCursor(ReminderType.StartStopReminder);
		
		String[] cols = {"ROUTE_ID","ROUTE_NAME","ROUTE_DIR","STOP_ID","STOP_NAME","ALARM_TIME"};
		
		int[] views = {R.id.reminder_route_id,R.id.reminder_route_name,R.id.reminder_route_dir,R.id.reminder_stop_id,R.id.reminder_stop_name,R.id.reminder_alarm_time};
		
		startStopRemindersAdapter = new SimpleCursorAdapter(context,R.layout.reminder_start_stop_row, remindersCursor, cols,views);
		
		startStopRemindersAdapter.setViewBinder(new ViewBinder(){

			@Override
			public boolean setViewValue(View view, Cursor cursor,
					int columnIndex) {
				
				if(columnIndex ==8){

					String value = cursor.getString(columnIndex);
					((TextView)view).setText(value.substring(value.indexOf('-')+1));
					
					return true;
					
				}
				
				return false;
			}
			
			
			
		});
		
		startStopRemindersListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long arg3) {
				Cursor cursor = (Cursor) startStopRemindersAdapter.getItem(position);
				setSelectedRow(position,view,cursor);			
				tabActivity.showDialog(REMINDER_MENU_DIALOG);
				
			}
		}
			
		);
		
		
		
		
		
	}


	public void onDestroy(){
		tabActivity.unregisterReceiver(receiver);
	}

	private void registerBroadcastReceiver(){
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(context.getString(R.string.reminders_tab_start_stop_update));
		intentFilter.addAction(context.getString(R.string.reminders_tab_end_stop_update));
		receiver = new RemindersUpdateBroadcastReciver();
		tabActivity.registerReceiver(receiver , intentFilter);
	}
	
	
	public class RemindersUpdateBroadcastReciver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(context.getString(R.string.reminders_tab_start_stop_update))){
				
				startStopRemindersAdapter.getCursor().requery();
			
			
			}else if(intent.getAction().equals(context.getString(R.string.reminders_tab_end_stop_update))){
				
				endStopRemindersAdapter.getCursor().requery();
				
			}
			
			
		}
		
	}

}
